/*
 * Copyright (c) 2009-2013 EvTech Project
 * All rights reserved.
 * 
 * This file is part of Game packet.
 *
 * Game packet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 *
 * Game packet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Game packet.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package fi.honkalampisaatio.game.utilities;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class MediaLoader {

	
	public static Clip createSoundClip(String soundFile) {
		Clip soundClip = null;
		if(soundFile!=null && !soundFile.equalsIgnoreCase("")) {
	        System.out.println("Creating clip "+soundFile);
			try {				
		         // Open an audio input stream.
		    	  AudioInputStream audioIn = AudioSystem.getAudioInputStream(new File(soundFile));
		         // Get a sound clip resource.
		    	  soundClip = AudioSystem.getClip();
		         // Open audio clip and load samples from the audio input stream.
		    	  soundClip.open(audioIn);
		         System.out.println("Sound clip created");
		         
		         
			} catch (Exception e) {
		        System.err.println("Couldn't create clip: " + soundFile);
				e.printStackTrace();
			} 
		}
		return soundClip;
	}

	public static BufferedImage createImage(String path, int maxHeight, int maxWidth) {
		BufferedImage img = null;
		if(path!=null && !path.equalsIgnoreCase("")) {
			try {
				img = ImageIO.read(new File(path));
				double scale = (double)img.getHeight()/maxHeight<(double)img.getWidth()/maxWidth?
						(double)maxWidth/img.getWidth():(double)maxHeight/img.getHeight();
				if(scale<1 && scale>0) {
					System.out.println("Scaling "+path+" size: "+img.getWidth()
							+", "+img.getHeight()+" factor="+scale);
					AffineTransform tx = new AffineTransform();
					tx.scale(scale, scale);
					AffineTransformOp op = new AffineTransformOp(tx, 
							AffineTransformOp.TYPE_BILINEAR);
					img = op.filter(img, null);
				}
			} catch (Exception e) {
		        System.err.println("Couldn't create image: " + path);
				e.printStackTrace();
			}
		}
		return img;
	}
}
